import {createRouter, createWebHistory, RouteRecordRaw} from 'vue-router';
import Index from '@src/views/login/Index.vue';
import {userStore} from "@src/store/user.ts";
import Error403 from "@src/views/error/Error403.vue";
import Error404 from "@src/views/error/Error404.vue";
import HomeIndex from "@src/views/home/HomeIndex.vue";

const routes: readonly RouteRecordRaw[] = [
    {
        path: '/',
        redirect: '/login',
        meta: {
            requiresAuth: false,
            requiredRoles: [],
        },
    },
    {
        path: '/login',
        name: 'Login',
        component: Index,
        meta: {
            requiresAuth: false,
            requiredRoles: [],
        },
    },
    {
        path: '/403',
        name: '403',
        component: Error403,
        meta: {
            requiresAuth: false,
            requiredRoles: [],
        }
    },
    {
        path: '/home',
        name: 'home',
        component: HomeIndex,
        meta: {
            requiresAuth: true,
            requiredRoles: ["User"],
        }
    },
    {
        path: '/404',
        name: '404',
        component: Error404,
        meta: {
            requiresAuth: false,
            requiredRoles: [],
        }
    }
];

const router = createRouter({
    history: createWebHistory(),
    routes,
});

function checkUserLoggedIn(): boolean {
    return userStore().userIsLogin;
}

function checkUserRoles(requiredRoles: String[]) {
    // Admin User Visitor
    return requiredRoles.includes(userStore().userRole);

}

router.beforeEach((to, from, next) => {
    const requiresAuth = to.meta.requiresAuth; // 是否需要登录权限
    const requiredRoles: String[] = to.meta.requiredRoles; // 路由所需的角色权限

    // 判断路由是否需要登录权限
    if (requiresAuth) {
        const isLoggedIn: boolean = checkUserLoggedIn(); // 检查用户是否已登录
        if (!isLoggedIn) {
            // 未登录，跳转到登录页面
            next('/login');
            return;
        }
    }

    // 判断路由是否需要角色权限
    if (requiredRoles.length) {
        const hasRequiredRoles = checkUserRoles(requiredRoles); // 检查用户是否具备所需的角色权限
        if (!hasRequiredRoles) {
            // 权限不足，跳转到无权限页面或其他处理方式
            next('/403');
            return;
        }
    }

    // 权限通过，继续导航到目标路由
    next();
});

export default router;
